<template>
  <view class="ai-chat-page">
    <view class="page-header">
      <text class="page-title">AI对话</text>
      <button class="clear-btn" @click="deleteChat" :disabled="loading">清除对话</button>
    </view>

    <!-- 对话记录区域 -->
    <scroll-view class="chat-messages" scroll-y="true" :scroll-top="scrollTop">
      <view class="message-list">
        <!-- 系统提示 -->
        <view class="system-message">
          <text>欢迎使用AI对话助手，请问有什么可以帮助您的？</text>
        </view>

        <!-- 用户消息 -->
        <view class="message-item user-message" v-for="(msg, index) in messages" :key="index">
          <view class="avatar">
            <image src="https://via.placeholder.com/40/667eea/ffffff?text=U" mode="aspectFill"></image>
          </view>
          <view class="message-content">
              <text>{{ msg.content }}</text>
            </view>
        </view>

        <!-- AI消息 -->
        <view class="message-item ai-message" v-for="(msg, index) in aiResponses" :key="index + 1000">
          <view class="avatar">
            <image src="https://via.placeholder.com/40/ff6b35/ffffff?text=AI" mode="aspectFill"></image>
          </view>
          <view class="message-content">
            <text>{{ msg.content }}</text>
            <text v-if="isStreaming" class="typing-indicator">...</text>
          </view>
        </view>
      </view>
    </scroll-view>

    <!-- 输入区域 -->
    <view class="input-area">
      <textarea class="message-input" v-model="inputMessage" placeholder="请输入您的问题..."></textarea>
      <button class="send-btn" @click="sendMessage" :disabled="loading">
        <text v-if="loading">发送中...</text>
        <text v-else>发送</text>
      </button>
    </view>
  </view>
</template>

<script setup>
import { ref, watch, onMounted } from 'vue'
import { aiAPI } from '../../utils/api.js'

const inputMessage = ref('')
const messages = ref([])
const aiResponses = ref([])
const scrollTop = ref(0)
const loading = ref(false)
const errorMessage = ref('')
const isStreaming = ref(false)
let currentAIContent = ''
let currentAIResponseIndex = -1
let abortController = null

// 监听消息变化，自动滚动到底部
watch([messages, aiResponses], () => {
  setTimeout(() => {
    scrollTop.value = 999999
  }, 100)
})

// 页面加载时获取历史对话
onMounted(() => {
  loadChatHistory()
})

// 加载历史对话
const loadChatHistory = async () => {
  try {
    loading.value = true
    const result = await aiAPI.getChat()
    if (result.code === '00000' && result.data) {
      // 处理历史对话数据
      const history = result.data
      // 这里假设history是一个包含用户消息和AI回复的数组
      // 需要根据实际数据结构调整
      messages.value = []
      aiResponses.value = []
      
      // 示例处理逻辑，实际需要根据后端返回的数据结构调整
      if (Array.isArray(history)) {
        history.forEach((item, index) => {
          if (index % 2 === 0) {
            messages.value.push({ content: item.content || item })
          } else {
            aiResponses.value.push({ content: item.content || item })
          }
        })
      }
    }
  } catch (error) {
    console.error('加载历史对话失败:', error)
    showError('加载历史对话失败，请稍后重试')
  } finally {
    loading.value = false
  }
}

// 发送消息
const sendMessage = () => {
  if (!inputMessage.value.trim()) return
  if (loading.value) return

  // 添加用户消息
  messages.value.push({
    content: inputMessage.value
  })

  // 清空输入框
  inputMessage.value = ''

  try {
    loading.value = true
    isStreaming.value = true
    
    // 准备接收AI回复的容器
    currentAIContent = ''
    currentAIResponseIndex = aiResponses.value.length
    aiResponses.value.push({
      content: ''
    })
    
    // 中止之前的请求（如果有）
    if (abortController) {
      abortController()
    }
    
    try {
      // 调用AI搜索接口 - SSE流格式
      abortController = aiAPI.search(
        messages.value[messages.value.length - 1].content,
        
        // 接收到消息时的回调
        (eventData) => {
          try {
            // 尝试解析SSE消息中的data字段
            let data;
            try {
              data = JSON.parse(eventData.data);
            } catch (parseError) {
              // 如果解析失败，尝试直接使用eventData.data
              console.warn('解析JSON失败，尝试直接使用原始数据:', parseError);
              data = { content: eventData.data };
            }
            
            if (data.content) {
              // 更新当前AI回复内容
              currentAIContent += data.content
              aiResponses.value[currentAIResponseIndex] = {
                content: currentAIContent
              }
              
              // 自动滚动到底部
              setTimeout(() => {
                scrollTop.value = 999999
              }, 100)
            }
          } catch (error) {
            console.error('处理SSE消息失败:', error)
            console.error('原始消息:', eventData.data)
          }
        },
        
        // 请求完成时的回调
        () => {
          console.log('AI回复完成')
          isStreaming.value = false
          loading.value = false
          abortController = null
        },
        
        // 请求错误时的回调
        (error) => {
          console.error('发送消息失败:', error)
          // 显示友好的错误消息
          let errorMessage = 'AI回复异常，请稍后重试';
          if (error.errMsg) {
            errorMessage = error.errMsg;
          } else if (error.message) {
            errorMessage = error.message;
          }
          showError(errorMessage)
          isStreaming.value = false
          loading.value = false
          abortController = null
          // 如果失败，移除刚才添加的用户消息
          if (messages.value.length > 0) {
            messages.value.pop()
          }
          // 移除空的AI回复
          if (aiResponses.value.length > 0 && currentAIResponseIndex >= 0 && !aiResponses.value[currentAIResponseIndex].content) {
            aiResponses.value.pop()
          }
        }
      )
    } catch (error) {
      console.error('发送消息过程中发生异常:', error)
      showError('系统错误，请稍后再试')
      isStreaming.value = false
      loading.value = false
      abortController = null
      // 如果失败，移除刚才添加的用户消息
      if (messages.value.length > 0) {
        messages.value.pop()
      }
      // 移除空的AI回复
      if (aiResponses.value.length > 0 && currentAIResponseIndex >= 0 && !aiResponses.value[currentAIResponseIndex].content) {
        aiResponses.value.pop()
      }
    }
  } catch (error) {
    console.error('发送消息失败:', error)
    showError('发送消息失败，请检查网络连接')
    isStreaming.value = false
    loading.value = false
    abortController = null
    // 如果失败，移除刚才添加的用户消息
    if (messages.value.length > 0) {
      messages.value.pop()
    }
    // 移除空的AI回复
    if (aiResponses.value.length > 0 && currentAIResponseIndex >= 0 && !aiResponses.value[currentAIResponseIndex].content) {
      aiResponses.value.pop()
    }
  }
}

// 删除对话
const deleteChat = async () => {
  try {
    loading.value = true
    const result = await aiAPI.deleteChat()
    if (result.code === '00000') {
      // 清空对话记录
      messages.value = []
      aiResponses.value = []
      uni.showToast({
        title: '对话已清除',
        icon: 'success'
      })
    } else {
      showError('清除对话失败，请稍后重试')
    }
  } catch (error) {
    console.error('删除对话失败:', error)
    showError('删除对话失败，请检查网络连接')
  } finally {
    loading.value = false
  }
}

// 显示错误信息
const showError = (msg) => {
  errorMessage.value = msg
  uni.showToast({
    title: msg,
    icon: 'none'
  })
  // 3秒后清除错误信息
  setTimeout(() => {
    errorMessage.value = ''
  }, 3000)
}
</script>

<style scoped>
.ai-chat-page {
  background: #f5f5f5;
  min-height: 100vh;
  display: flex;
  flex-direction: column;
}

.page-header {
    background: #fff;
    padding: 30rpx;
    text-align: center;
    border-bottom: 1rpx solid #f0f0f0;
    display: flex;
    justify-content: space-between;
    align-items: center;
    position: relative;
  }
  
  .clear-btn {
    background: #f5f5f5;
    color: #666;
    font-size: 24rpx;
    padding: 10rpx 20rpx;
    border-radius: 30rpx;
    line-height: normal;
  }
  
  .page-title {
  font-size: 36rpx;
  font-weight: bold;
  color: #333;
}

.chat-messages {
  flex: 1;
  padding: 20rpx;
  overflow-y: auto;
}

.message-list {
  display: flex;
  flex-direction: column;
  gap: 20rpx;
}

.system-message {
  background: #e8f4ff;
  padding: 20rpx;
  border-radius: 10rpx;
  font-size: 26rpx;
  color: #333;
  text-align: center;
}

.message-item {
  display: flex;
  max-width: 85%;
}

.user-message {
  align-self: flex-end;
  flex-direction: row-reverse;
}

.ai-message {
  align-self: flex-start;
}

.avatar {
  width: 80rpx;
  height: 80rpx;
  border-radius: 50%;
  overflow: hidden;
  margin: 0 15rpx;
}

.avatar image {
  width: 100%;
  height: 100%;
}

.message-content {
  padding: 20rpx;
  border-radius: 20rpx;
  font-size: 28rpx;
  word-break: break-all;
}

.user-message .message-content {
  background: #667eea;
  color: #fff;
  border-top-right-radius: 5rpx;
}

.ai-message .message-content {
  background: #fff;
  color: #333;
  border-top-left-radius: 5rpx;
}

.typing-indicator {
  animation: typing 1.4s infinite both;
  color: #999;
  font-size: 32rpx;
}

@keyframes typing {
  0% { opacity: 0.3; }
  50% { opacity: 1; }
  100% { opacity: 0.3; }
}

.input-area {
  display: flex;
  padding: 20rpx;
  background: #fff;
  border-top: 1rpx solid #f0f0f0;
}

.message-input {
  flex: 1;
  height: 120rpx;
  padding: 20rpx;
  background: #f5f5f5;
  border-radius: 60rpx;
  font-size: 28rpx;
  color: #333;
}

.send-btn {
  width: 120rpx;
  height: 120rpx;
  margin-left: 20rpx;
  background: #ff6b35;
  color: #fff;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 28rpx;
}
</style>